package com.ruoyi.system.controller;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.system.domain.ProductHistory;
import com.ruoyi.system.mapper.ProductHistoryMapper;
import com.ruoyi.system.mapper.ProductZhangMapper;
import com.ruoyi.system.service.IProductHistoryService;
import org.apache.poi.hpsf.Decimal;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.ProductZhang;
import com.ruoyi.system.service.IProductZhangService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * zhangController
 * 
 * @author Alexis
 * @date 2024-02-26
 */
@RestController
@RequestMapping("/system/zhang")
public class ProductZhangController extends BaseController
{
    @Autowired
    private IProductZhangService productZhangService;

    @Resource
    private ProductZhangMapper productZhangMapper;

    @Resource
    private IProductHistoryService productHistoryService;

    @Resource
    private RedisTemplate<String,List<ProductZhang>> redisTemplate;

    @Resource
    private ProductHistoryMapper productHistoryMapper;

    /**
     * 查询zhang列表
     */
    @PreAuthorize("@ss.hasPermi('system:zhang:list')")
    @GetMapping("/list")
    public TableDataInfo list(ProductZhang productZhang)
    {
        startPage();
        List<ProductZhang> list = productZhangService.selectProductZhangList(productZhang);
        List<ProductZhang> collect = list.stream().filter(i -> Objects.equals(i.getDeleteSoft(), 0)).collect(Collectors.toList());
        return getDataTable(collect);
    }

    /**
     * 导出仓库列表
     */
    @PreAuthorize("@ss.hasPermi('system:zhang:export')")
    @Log(title = "zhang", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ProductZhang productZhang)
    {
        List<ProductZhang> list = productZhangService.selectProductZhangList(productZhang);
        ExcelUtil<ProductZhang> util = new ExcelUtil<ProductZhang>(ProductZhang.class);
//        util.exportExcel(response, list, "商品数据");

        util.exportEasyExcel(response,list);
    }


    /**
     * 导出仓库列表
     */
    @PostMapping("/exportProduct")
    public void exportProduct(HttpServletResponse response)
    {
        List<ProductZhang> list = redisTemplate.opsForValue().get("list");
        ExcelUtil<ProductZhang> util = new ExcelUtil<ProductZhang>(ProductZhang.class);
        if (list != null) {
            util.exportEasyExcel(response,list);
        }
    }

    /**
     * 获取zhang详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:zhang:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return success(productZhangService.selectProductZhangById(id));
    }

    /**
     * 新增zhang
     */
    @PreAuthorize("@ss.hasPermi('system:zhang:add')")
    @Log(title = "zhang", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ProductZhang productZhang)
    {
        productZhang.setDeleteSoft(0);
        return toAjax(productZhangService.insertProductZhang(productZhang));
    }

    /**
     * 修改zhang
     */
    @PreAuthorize("@ss.hasPermi('system:zhang:edit')")
    @Log(title = "zhang", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ProductZhang productZhang)
    {
        return toAjax(productZhangService.updateProductZhang(productZhang));
    }

    /**
     * 生成单据时减去库存
     */
    @PostMapping("/creat")
    public AjaxResult upset(HttpServletResponse response,@RequestBody ProductHistory productHistory)
    {
        List<ProductZhang> list = new ArrayList<>();
        ProductZhang productZhangCopy = new ProductZhang();
        //获取种类
        String[] product = productHistory.getListClass().split(",");
        //获取数量
        String[] number = productHistory.getNumber().split(",");
        if (Objects.equals(product.length,number.length)){
            for (int i=0;i<product.length;i++){
                ProductZhang productZhang = productZhangService.selectProductZhangById(product[i]);
                BigDecimal numbers = new BigDecimal(number[i]);
                //相减的数据，保存
                productZhang.setNumber(productZhang.getNumber().subtract(numbers));
                productZhang.setAllPrice(productZhang.getPrice().multiply(productZhang.getNumber()));
                //保存数据
                BeanUtils.copyProperties(productZhang,productZhangCopy);
                productZhangCopy.setNumber(numbers);
                productZhangCopy.setAllPrice(numbers.multiply(productZhang.getPrice()));
                list.add(productZhangCopy);
                //保存现有数据
                productZhangService.updateProductZhang(productZhang);
            }
        }
        //存入redis,设置有效时间
        redisTemplate.opsForValue().set("list",list,1, TimeUnit.HOURS);
        //设置有效
        productHistory.setEffective(1L);
        //设置创建时间
        productHistory.setCreateTime(new Date());
        //自动设置名字
        productHistory.setName("生成时间:"+new Date());
        //保存数据
        return toAjax(productHistoryService.insertProductHistory(productHistory));
    }



    /**
     * 撤销单据时加上库存
     */
    @PreAuthorize("@ss.hasPermi('system:zhang:edit')")
    @Log(title = "zhang", businessType = BusinessType.UPDATE)
    @PostMapping("/reset")
    public AjaxResult reset(@RequestBody ProductHistory productHistory)
    {
        //获取种类
        String[] product = productHistory.getListClass().split(",");
        //获取数量
        String[] number = productHistory.getNumber().split(",");
        if (Objects.equals(product.length,number.length)){
            for (int i=0;i<product.length;i++){
                ProductZhang productZhang = productZhangService.selectProductZhangById(product[i]);
                BigDecimal numbers = new BigDecimal(Integer.parseInt(number[i]));
                //加入之前相减的数据，保存
                productZhang.setNumber(productZhang.getNumber().add(numbers));
                //得到总价
                productZhang.setAllPrice(productZhang.getNumber().multiply(productZhang.getPrice()));
                //保存数据
                productZhangService.updateProductZhang(productZhang);
            }
        }
        //设置无效
        productHistory.setEffective(0L);
        //保存数据
        return toAjax(productHistoryService.updateProductHistory(productHistory));
    }


    /**
     * 撤销单据时加上库存
     */
    @GetMapping("/detail")
    public List<ProductZhang> detail(String id)
    {
        ProductHistory productHistory = productHistoryService.selectProductHistoryById(id);

        String[] split = productHistory.getListClass().split(",");
        String[] number = productHistory.getNumber().split(",");
        List<ProductZhang> list = new ArrayList<>();
        for (int i =0;i<split.length;i++){
            ProductZhang productZhang = productZhangService.selectProductZhangById(split[i]);
            BigDecimal numbers = new BigDecimal(Integer.parseInt(number[i]));
            //相减的数据，保存
            productZhang.setNumber(productZhang.getNumber().add(numbers));
            productZhang.setAllPrice(productZhang.getNumber().multiply(productZhang.getPrice()));
            //保存数据
            list.add(productZhang);
        }
        //保存数据
        return list;
    }



    /**
     * 删除zhang
     */
    @PreAuthorize("@ss.hasPermi('system:zhang:remove')")
    @Log(title = "zhang", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(productZhangService.deleteProductZhangByIds(ids));
    }
}
